<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="container"></div>
    <button id="btn-change">change</button>
    <script src="https://cdn.bootcss.com/snabbdom/0.7.3/snabbdom.js"></script>
    <script src="https://cdn.bootcss.com/snabbdom/0.7.3/snabbdom-class.js"></script>
    <script src="https://cdn.bootcss.com/snabbdom/0.7.3/snabbdom-props.js"></script>
    <script src="https://cdn.bootcss.com/snabbdom/0.7.3/snabbdom-style.js"></script>
    <script src="https://cdn.bootcss.com/snabbdom/0.7.3/snabbdom-eventlisteners.min.js"></script>
    <script src="https://cdn.bootcss.com/snabbdom/0.7.3/h.js"></script>
    <script>
        // 只有改变的栏目才闪烁，也就是进行重绘，数据没有改变
        // 的栏目还是保持原样，这样就大大节省了浏览器重新渲染的开销
        let snabbdom = window.snabbdom;

        // 定义patch
        let patch = snabbdom.init([
            snabbdom_class,
            snabbdom_props,
            snabbdom_style,
            snabbdom_eventlisteners
        ]);

        // 定义h
        let h = snabbdom.h;

        const data = [{
                name: 'peter',
                age: '20',
                address: '北京'
            },
            {
                name: 'bob',
                age: '18',
                address: '武汉'
            },
            {
                name: 'lisa',
                age: '19',
                address: '南昌'
            }
        ];
        data.unshift({name: '姓名', age: '年龄', address: '地址'});

        let container = document.getElementById('container');
        let vnode;
        const render = (data) => {
            let newVnode = h('table', {}, data.map(item => {
                let tds = [];
                for (let i in item) {
                    if (item.hasOwnProperty(i)) {
                        tds.push(h('td', {}, item[i] + ''));
                    }
                }
                return h('tr', {}, tds);
            }))
            if (vnode) {
                patch(vnode, newVnode);
            } else {
                patch(container, newVnode)
            }
            vnode = newVnode;
        }

        render(data);

        let btnChange = document.getElementById('btn-change');
        btnChange.addEventListener('click', () => {
            data[1].age = 30;
            data[2].address = '上海';
            // re-render
            render(data);
        })
    </script>
</body>

</html>